//
//  SRInfoViewController.m
//  SportRing
//
//  Created by 微他 on 15-1-20.
//  Copyright (c) 2015年 HotOne. All rights reserved.
//

#import "SRInfoViewController.h"
#import <UIImageView+AFNetworking.h>
#import "SRMe+Cate.h"
#import "UndertheFrame.h"
#import "GLScrollView.h"
#import "PickerView.h"
#import "SRAccountNetService.h"
#import "SRUserBLEService.h"

@interface SRInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UndertheFrameDelegate,PickerViewDelegate,UIScrollViewDelegate>
{
    GLScrollView *_scrollview;
    NSArray *_arr;
    UITableView *_tableView;
    SRMe *_me;
    UIImageView *_avtar;
    UITextField *_textField1;
    UITextField *_textField2;
    UIImageView *_imageView;
    UILabel *_titleLabel;
    UIButton *_back;
}
@end

@implementation SRInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [SetFontColorProperty setFontColor:255 float2:242 float3:233];
    _arr = @[@"昵称",@"性别",@"年龄",@"身高",@"体重"];
    _me = [SRMe currentUser];
    [self initView];
}

- (void)initView
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 264)];
    _imageView.image = [UIImage imageNamed:@"infobg"];
    [self.view addSubview:_imageView];
    
    _scrollview = [[GLScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _scrollview.delegate = self;
    [self.view addSubview:_scrollview];
    
    _avtar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    _avtar.layer.cornerRadius = 40;
    _avtar.layer.masksToBounds = YES;
    _avtar.userInteractionEnabled = YES;
    [_avtar setImageWithURL:[NSURL URLWithString:_me.headPhoto] placeholderImage:[UIImage imageNamed:@"头像"]];
    _avtar.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMaxY(_imageView.frame));
    _avtar.tag = 666;
    [_scrollview addSubview:_avtar];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_avtar.frame) + 10, CGRectGetWidth(self.view.bounds), 250)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.scrollEnabled = NO;
    [_scrollview addSubview:_tableView];
    
    _scrollview.contentSize = CGSizeMake(0, CGRectGetMaxY(_tableView.frame)+10);
    
    _back = [UIButton buttonWithType:UIButtonTypeCustom];
    [_back setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    _back.frame = CGRectMake(0, 24, 60, 40);
    _back.imageEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 34);
    [_back addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    _back.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin;
    [_scrollview addSubview:_back];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
    _titleLabel.text = @"个人信息";
    _titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.center = CGPointMake(CGRectGetMidX(self.view.bounds), 42);
//    _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    [_scrollview addSubview:_titleLabel];
    
    _textField1 = [[UITextField alloc] initWithFrame:CGRectMake(20, 5, 200, 20)];
    _textField1.hidden = YES;
    [self.view addSubview:_textField1];
    
    //添加toolbar适配键盘
    UIToolbar *topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    [topView setBarStyle:UIBarStyleDefault];
    _textField2 = [[UITextField alloc] initWithFrame:CGRectMake(0, 5, 250, 30)];
    _textField2.layer.cornerRadius = 4;
    _textField2.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem * btnSpace1 = [[UIBarButtonItem alloc]initWithCustomView:_textField2];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"确定", nil) style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    doneButton.tintColor = [UIColor colorWithRed:144.0/255.0 green:87.0/255.0 blue:192.0/255.0 alpha:1];
    topView.items = @[btnSpace1, doneButton];
    [_textField1 setInputAccessoryView:topView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat yOffset = _scrollview.contentOffset.y;
    CGFloat factor = ((ABS(yOffset) +264) *CGRectGetWidth(self.view.frame)) /264;
    //    NSLog(@"%f",factor);
    CGRect newFrame;
    if (yOffset < 0) {
        newFrame = CGRectMake(-(factor -CGRectGetWidth(self.view.frame)) /2, 0,
                              factor, 264 +ABS(yOffset));
        _imageView.frame = newFrame;
        //center.y = 128.5
        _back.center = CGPointMake(30, 42 +yOffset);
        _titleLabel.center = CGPointMake(CGRectGetMidX(self.view.frame), 42 +yOffset);
    }
    else {
        newFrame = _imageView.frame;
        newFrame.origin.y = -yOffset;
        _imageView.frame = newFrame;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIbentify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIbentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIbentify];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = _arr[indexPath.row];
    if (indexPath.row == 0) {
        cell.detailTextLabel.text = _me.nickName;
    }
    else if (indexPath.row == 1) {
        
        if ([_me.gender integerValue] == SRGenderFemale)
        {
            cell.detailTextLabel.text = @"女";
        }
        if ([_me.gender integerValue] == SRGenderMale)
        {
            cell.detailTextLabel.text = @"男";
        }
        
    }else if (indexPath.row == 2)
    {
        if (![_me.birthday isEqualToString:@""]) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy"];
            NSInteger temp = [[formatter stringFromDate:[NSDate date]] integerValue] - [[_me.birthday substringToIndex:4] integerValue];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld岁",temp];
        }
        
    }else if (indexPath.row == 3)
    {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%ldcm",[_me.height integerValue]];
    }else if (indexPath.row == 4)
    {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%ldkg",[_me.weight integerValue]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        [_textField1 becomeFirstResponder];
        [_textField2 becomeFirstResponder];
        _textField2.text = _me.nickName;
    }else if (indexPath.row == 1)
    {
        UndertheFrame *pickerView = [[UndertheFrame alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) isSex:YES];
        pickerView.tag = 199;
        pickerView.delegate = self;
        pickerView.alpha = 0;
        [self.view addSubview:pickerView];
        
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            pickerView.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
//        [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:30 options:UIViewAnimationOptionCurveEaseInOut animations:^{
//            pickerView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
//            pickerView.alpha = 1;
//        } completion:nil];
        
    }else if (indexPath.row == 2)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy"];
        NSInteger temp = [[formatter stringFromDate:[NSDate date]] integerValue] - [[_me.birthday substringToIndex:4] integerValue];
        PickerView *pickerView = [[PickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
        [pickerView ageArea];
        pickerView.tag = 200;
        pickerView.delegete = self;
        pickerView.alpha = 0;
        [self.view addSubview:pickerView];
        if (temp == 0) {
            [pickerView defaultSelect:@"24"];
        }else
        {
            [pickerView defaultSelect:[NSString stringWithFormat:@"%ld",(long)temp]];
        }
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            pickerView.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
    }else if (indexPath.row == 3)
    {
        PickerView *pickerView = [[PickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
        [pickerView heightArea];
        pickerView.tag = 201;
        pickerView.delegete = self;
        pickerView.alpha = 0;
        [self.view addSubview:pickerView];
        if ([_me.height integerValue] == 0) {
            [pickerView defaultSelect:@"170"];
        }else
        {
            [pickerView defaultSelect:[NSString stringWithFormat:@"%@",_me.height]];
        }
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            pickerView.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
    }else if (indexPath.row == 4)
    {
        PickerView *pickerView = [[PickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
        [pickerView weightArea];
        pickerView.tag = 202;
        pickerView.delegete = self;
        pickerView.alpha = 0;
        [self.view addSubview:pickerView];
        if ([_me.weight integerValue] == 0) {
            [pickerView defaultSelect:@"55"];
        }else
        {
            [pickerView defaultSelect:[NSString stringWithFormat:@"%@",_me.weight]];
        }
        [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            pickerView.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (touch.view.tag == 666) {
        UndertheFrame *under = [[UndertheFrame alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) isSex:NO];
        under.delegate = self;
        [self.view addSubview:under];
    }
    if (touch.view.tag == 200 || touch.view.tag == 201 || touch.view.tag == 202 || touch.view.tag == 199) {
        
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            touch.view.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [touch.view removeFromSuperview];
            }
        }];
    }
    [_textField2 resignFirstResponder];
    [_textField1 resignFirstResponder];
}

- (void)pickerViewDelegatestr1:(NSString *)str1
{
    if ([str1 hasSuffix:@"岁"]) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy"];
        NSInteger temp = [[formatter stringFromDate:[NSDate date]] integerValue] - [str1 integerValue];
        NSString *str = [NSString stringWithFormat:@"%ld-01-01",temp];
        NSDate *date = [NSDate dateFromString:str];
        [self didModifyBirthDay:date];
        
    }
    else if ([str1 hasSuffix:@"cm"]) {
        
        [self didModifyHeight:[str1 integerValue]];
    }
    else if ([str1 hasSuffix:@"kg"]) {
        
        [self didModifyWeight:[str1 integerValue]];
    }
}

- (void)undertheStr:(NSString *)str
{
    if ([str isEqualToString:@"男"]) {
        [self didModifySex:SR_SEX_TYPE_MALE];
    }
    if ([str isEqualToString:@"女"]) {
        [self didModifySex:SR_SEX_TYPE_FAMALE];
    }
}

- (void)backBtnClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)undertheFrame:(UIImage *)image
{
    _avtar.image = image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//------------------------------------------------
- (void)didModifyNickname:(NSString *)nickname
{
    [SVProgressHUD show];
    
    [[SRMe currentUser] configAttributesWithBlock:^(SRMe *meSelf) {
        meSelf.nickName = nickname;
    }];
    
    [[SRAccountNetService updateProfileWithNickName:nickname
                                           birthDay:_me.birthday
                                             weight:_me.weight
                                             height:_me.height
                                             gender:_me.gender]
     subscribeNext:^(id x) {
         
         [SVProgressHUD dismiss];
         [_tableView reloadData];
     } error:^(NSError *error) {
         
         [SVProgressHUD showErrorWithStatus:@"修改个人昵称失败"];
     }];
}

- (void)didModifySex:(SR_SEX_TYPE )sexType
{
    SRGender gender;
    
    if (sexType == SR_SEX_TYPE_MALE)
    {
        gender = SRGenderMale;
    }
    if (sexType == SR_SEX_TYPE_FAMALE)
    {
        gender = SRGenderFemale;
    }
    
    [_me configAttributesWithBlock:^(SRMe *meSelf) {
        meSelf.gender = @(gender);
    }];
    [SRUserBLEService updateMe:_me];
    
    [SVProgressHUD show];
    
    [[SRAccountNetService updateProfileWithNickName:_me.nickName
                                           birthDay:_me.birthday ? _me.birthday : @""
                                             weight:_me.weight
                                             height:_me.height
                                             gender:@(gender)]
     subscribeNext:^(id x) {
         [SVProgressHUD dismiss];
         [_tableView reloadData];
     } error:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"修改个人性别失败"];
     }];
}
- (void)didModifyBirthDay:(NSDate *)birthDay
{
    [_me configAttributesWithBlock:^(SRMe *meSelf) {
        meSelf.birthday = [@([birthDay year]) stringValue];
    }];
    [SRUserBLEService updateMe:_me];
    
    [SVProgressHUD show];
    [[SRAccountNetService updateProfileWithNickName:_me.nickName
                                           birthDay:[birthDay formattedBy_yyyyMMdd]
                                             weight:_me.weight
                                             height:_me.height
                                             gender:_me.gender]
     subscribeNext:^(id x) {
         [SVProgressHUD dismiss];
         [_tableView reloadData];
     } error:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"修改个人生日失败"];
     }];
}

- (void)didModifyWeight:(NSInteger)weight
{
    [_me configAttributesWithBlock:^(SRMe *meSelf) {
        meSelf.weight = @(weight);
    }];
    [SRUserBLEService updateMe:_me];
    
    [SVProgressHUD show];
    
    [[SRAccountNetService updateProfileWithNickName:_me.nickName
                                           birthDay:_me.birthday
                                             weight:[NSNumber numberWithLong:weight]
                                             height:_me.height
                                             gender:_me.gender]
     subscribeNext:^(id x) {
         [SVProgressHUD dismiss];
         [_tableView reloadData];
     } error:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"修改个人体重失败"];
     }];
}

- (void)didModifyHeight:(NSInteger)height
{
    [_me configAttributesWithBlock:^(SRMe *meSelf) {
        meSelf.height = @(height);
    }];
    [SRUserBLEService updateMe:_me];
    
    [SVProgressHUD show];
    
    [[SRAccountNetService updateProfileWithNickName:_me.nickName
                                           birthDay:_me.birthday
                                             weight:_me.weight
                                             height:[NSNumber numberWithLong:height]
                                             gender:_me.gender]
     subscribeNext:^(id x) {
         [SVProgressHUD dismiss];
         [_tableView reloadData];
     } error:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"修改个人身高失败"];
     }];
}

- (void)dismissKeyBoard
{
    if (![_textField2.text isEqualToString:_me.nickName]) {
        [self didModifyNickname:_textField2.text];
    }
    [_textField2 resignFirstResponder];
    [_textField1 resignFirstResponder];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
